/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import Control.exceptions.NonexistentEntityException;
import Control.exceptions.PreexistingEntityException;
import Entidades.Marca;
import Entidades.Modelo;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author luksCastro
 */
public class MarcaJpaController {
    
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public MarcaJpaController(UserTransaction utx, EntityManagerFactory emf){
        this.utx = utx;
        this.emf = emf;
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public EntityManager getEntityManager(){
        return emf.createEntityManager();
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public void create(Marca marca)throws Exception, PreexistingEntityException{
        if (marca.getModeloList() == null) {
            marca.setModeloList(new ArrayList<Modelo>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            
            List<Modelo> attachedModeloList = new ArrayList<Modelo>();
            for(Modelo modeloListModeloToAttach : marca.getModeloList()){
                modeloListModeloToAttach = em.getReference(modeloListModeloToAttach.getClass(), modeloListModeloToAttach.getIdModelo());
                attachedModeloList.add(modeloListModeloToAttach);
            }
            marca.setModeloList(attachedModeloList);
            em.persist(marca);
            //--------------------------------------
            for(Modelo modeloListModelo : marca.getModeloList()){
                Marca oldMarcaidMarcaOfModeloListModelo = modeloListModelo.getIdMarca();
                modeloListModelo.setIdMarca(marca);
                modeloListModelo = em.merge(modeloListModelo);
                if(oldMarcaidMarcaOfModeloListModelo != null){
                    oldMarcaidMarcaOfModeloListModelo.getModeloList().remove(modeloListModelo);
                    oldMarcaidMarcaOfModeloListModelo = em.merge(oldMarcaidMarcaOfModeloListModelo);
                }
            }
            
            em.getTransaction().commit();
        } catch (Exception ex) {
            if(findMarca(marca.getIdMarca())!=null){
                throw new PreexistingEntityException("La marca "+marca+" ya existe", ex);                
            }
            throw ex;
        }finally{
            if(em!=null){
                em.close();
            }
        }        
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public Marca findMarca(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Marca.class, id);
        } finally {
            em.close();
        }
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public Marca findMarca(String nombMarca) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Marca as o where o.nombreMarca ='"+nombMarca+"'");
            return (Marca) q.getSingleResult();
        } finally {
            em.close();
        }
    }
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    public List<Marca> findMarcaEntities() {
        return findMarcaEntities(true, -1, -1);
    }
    //-----------------------------------------------------------------------
    public List<Marca> findMarcaEntities(int maxResults, int firstResult) {
        return findMarcaEntities(false, maxResults, firstResult);
    }
    //-----------------------------------------------------------------------
    private List<Marca> findMarcaEntities(boolean all, int maxResults, int firstResult) {
       EntityManager em = getEntityManager();
       try {
           Query q = em.createQuery("select object(o) from Marca as o ORDER BY o.nombreMarca asc");
           if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
           }
           return q.getResultList();
       } finally {
            em.close();
       }
    }
    //------------------------------------------------------------------------
    public boolean destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();            
            Marca marca;
            try {
                marca = em.getReference(Marca.class, id);                
                marca.getIdMarca();                
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("La marca con id " + id + " no existe.", enfe);
            }
            List<Modelo> modeloList = marca.getModeloList();
            if (modeloList.isEmpty()) {
                em.remove(marca);
                em.getTransaction().commit();
                return true;
            } else {
                return false;
            }            
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
